<template>
  <el-dialog class="user-dialog" v-bind="$attrs" v-on="$listeners">
    <div class="el-dialog-body-child" v-closeSelect>
      <el-form ref="queryForm" :model="queryParams" label-width="80px" :inline="true" class="search-form clearfix">
        <el-form-item class="search-field fl five-per-row" label="用户名" prop="userName">
          <el-input v-model.trim="queryParams.userName" placeholder="请输入用户名" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item class="search-field fl five-per-row" label="手机号" prop="phoneNumber">
          <el-input v-model.trim="queryParams.phoneNumber" placeholder="请输入手机号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item class="search-field fl" label="性别" prop="sex">
          <el-select-dict dictType="SEX" v-model="queryParams.sex" placeholder="请选择性别" clearable
            @dictChange="handleQuery" />
        </el-form-item>
        <div class="fr">
          <el-button plain @click="resetQuery">重 置</el-button>
          <el-button type="primary" @click="handleQuery">查 询</el-button>
        </div>
      </el-form>
      <div class="table-wrap">
        <div class="tips-box">
          <el-tag type="warning">温馨提示：重新搜索后，需重新勾选并点击保存方可见效。</el-tag><el-button class="search-all-selected"
            type="primary" :disabled="isQueryAllSelected" @click="handleSearchAllSelected"
            size="small">点击查看已分配的用户</el-button>
        </div>
        <div class="table-box">
          <el-table ref="roleUserTable" :class="{ 'empty': list.length === 0 }" empty-text=" " v-loading="loading"
            :data="list" row-key="userId" @selection-change="handleSelectionChange" @row-click="clickRow"
            height="526px">
            <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
            <el-table-column label="用户名" prop="userName" align="center" min-width="120px" />
            <el-table-column-dict maskType="mobile" label="手机号" prop="phoneNumber" align="center" min-width="120px" />
            <el-table-column-dict dictType="SEX" label="用户性别" prop="sex" align="center" min-width="80px" />
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <template>
        <el-button @click="$emit('close')">关 闭</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </template>
    </div>
  </el-dialog>
</template>
<script>
import { userApi, roleApi } from "@/api"
export default {
  props: {
    roleId: {
      type: [String, Number],
      default: ""
    }
  },
  watch: {
    roleId(val) {
      if (val) {
        this.isQueryAllSelected = false
        roleApi.getUserIdsByRoleId({ roleId: val }).then((data) => {
          this.userIds = data.map((item) => item.userId)
          // 渲染选中表格
          this.renderSelectTable()
        })
      }
    }
  },
  data() {
    return {
      isQueryAllSelected: false, // 是否已点击查询所有已分配
      //搜索条件参数
      queryParams: {
        userName: "", // 用户名称
        phoneNumber: "", // 手机号
        sex: "", // 性别
        userIds: "", // 根据用户id列表 ,隔开
        status: "1", // 只查询启用状态的
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      list: [],
      total: 0,
      ids: [], // 已选中的项
      userIds: [], // 已分配的用户id列表
      isRenderPage: [], // 已渲染过的列表页码
      listSelectIds: [] // 已渲染过的用户id数据
    }
  },
  created() {
    //获取列表
    this.getList()
  },
  methods: {
    // 查询所有已分配的角色
    handleSearchAllSelected() {
      if (this.isQueryAllSelected) { return }
      this.isQueryAllSelected = true // 是否查询已分配
      if (this.userIds.length === 0) {
        this.$modal.msgWarning("该角色暂无分配任何人员，请直接分配")
        return
      }
      this.queryParams.userIds = this.userIds.join(",")
      this.resetForm("queryForm")
      this.handleQuery({ isSearchAllSelected: true })
    },
    // 清空选项
    clearSelection(isSearch) {
      this.$refs.roleUserTable.clearSelection()
      this.isRenderPage = []
      this.listSelectIds = []
      if (isSearch) {
        return
      }
      this.resetForm("queryForm")
      this.queryParams.pageNum = 1
      this.queryParams.userIds = ""
      this.userIds = []
      this.getList()
    },
    // 渲染选中的数据
    renderSelectTable() {
      if (
        this.isRenderPage.includes(this.queryParams.pageNum) ||
        this.userIds.length === 0
      ) {
        return
      }
      this.isRenderPage.push(this.queryParams.pageNum)
      for (let i = 0; i < this.list.length; i++) {
        const item = this.list[i]
        if (this.userIds.includes(item.userId)) {
          this.listSelectIds.push(item.userId)
          this.$nextTick(() => {
            this.$refs.roleUserTable.toggleRowSelection(item, true)
          })
        }
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
    },
    //点击行
    clickRow(row) {
      this.$refs.roleUserTable.toggleRowSelection(row)
    },
    /** 搜索按钮操作 data.isSearchAllSelected 是否是查询全部已选列表 不是的话 把搜索条件的roleIds 设置为  "" */
    handleQuery(data) {
      if (!data || !data.isSearchAllSelected) {
        this.isQueryAllSelected = false
        this.queryParams.userIds = ""
      }
      // 点击搜索时 清空选项 重新开始
      this.clearSelection(true)
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.isQueryAllSelected = false
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 查询角色列表 */
    getList(options) {
      if (options?.type === "sizeChange") {
        this.isRenderPage = []
      }
      this.loading = true
      userApi
        .getList(this.queryParams)
        .then((response) => {
          this.list = response.rows
          this.total = response.total
          this.loading = false
          this.renderSelectTable()
        })
        .catch((err) => {
          if (err?.name === "CanceledError") {
            return
          }
          this.loading = false
        })
    },
    // 保存
    async save() {
      // 获取已选中ids没有，listSelectIds有的userId：说明这些用户被移除勾选了
      const removeIds = [...new Set(this.listSelectIds)].filter(
        (item) => !new Set(this.ids).has(item)
      )
      // 获取已选中ids有，listSelectIds没有的userId： 说明这些是新增的
      const addIds = [...new Set(this.ids)].filter(
        (item) => !new Set(this.listSelectIds).has(item)
      )
      // 利用最先的userIds 去除移除勾选的 添加新增的
      let resultIds = []
      // 去掉移除勾选的
      resultIds = [...new Set(this.userIds)].filter(
        (item) => !new Set(removeIds).has(item)
      )
      // 添加新增的
      resultIds = resultIds.concat(addIds)

      let isConfirm = true
      if (
        resultIds.includes(this.userInfo.userId) ||
        this.userIds.includes(this.userInfo.userId)
      ) {
        await this.$modal
          .confirm("此操作将影响到您的权限，是否继续操作？")
          .catch((err) => {
            // 取消或者关闭
            isConfirm = false
          })
      }
      if (!isConfirm) {
        return
      }
      const params = {
        roleId: this.roleId,
        userIds: resultIds,
        oldUserIds: this.userIds
      }
      roleApi
        .setUserIdsByRoleId(params)
        .then((data) => {
          if (
            resultIds.includes(this.userInfo.userId) ||
            this.userIds.includes(this.userInfo.userId)
          ) {
            this.$store.dispatch("user/getUserInfo")
          }
          this.$modal.msgSuccess(data.msg)
          this.$emit("close")
        })
        .catch((err) => {
          this.$emit("close")
        })
    }
  }
}
</script>
<style lang="scss" scoped></style>
